package com.kk.score.controller;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kk.score.dao.GradeDao;
import com.kk.score.dao.TaskDao;
import com.kk.score.dao.UserDao;
import com.kk.score.entity.*;
import com.kk.score.entity.vo.UserVo;
import com.kk.score.service.*;
import com.kk.score.service.impl.JWCJLoginServiceImpl;
import com.kk.score.utils.PageUtils;
import com.kk.score.utils.R;
import com.kk.score.utils.SpringSecurityUtils;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author KK
 * @email 409592048@qq.com
 * @date 2022-11-02 12:28:00
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JWCJLoginServiceImpl jwcjLoginService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private PushGradeService pushGradeService;

    @Autowired
    private GradeDao gradeDao;

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private PushService pushService;

    @PostMapping("/login")
    public R login(@RequestBody @Validated UserVo userVo) {
        Boolean flag;
        //******首次登录******
        if (Objects.isNull(userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, userVo.getUsername())))) {
            //教务系统登录
            String cookie = jwcjLoginService.isT(userVo.getUsername(), userVo.getPassword(), userVo.getEncoded());
            if (cookie.equals("false")) {
                return R.error("教务系统账号密码错误！");
            }
            //验证教务系统账号密码是否正确  info里面有 学院、专业、年级、班级、姓名、电话、生日、政治面貌
            UserVo info = jwcjLoginService.getInfo(cookie);
            //不正确
            if (Objects.isNull(info)) {
                //获取 部门和职位出错
                return R.error("登录失败，请联系管理员！");
            }
            //设置账号密码
            info.setUsername(userVo.getUsername());
            info.setPassword(userVo.getPassword());
            flag = userService.login(info);
        } else {
            flag = userService.login(userVo);
        }
        flag = userService.login(userVo);
        return R.ok().put("data", flag);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);

        return R.ok().put("data", page);
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public R changePassword(@RequestBody UserEntity user) {
        user.setUid(SpringSecurityUtils.getUid());
        return userService.changePassword(user);
    }

    /**
     * 重置密码
     */
    @PostMapping("/re")
    public R re(@RequestBody String[] uids) {
        return userService.changePassword(new UserEntity(uids[0], "123456"));
    }

    /**
     * 信息
     */
    @GetMapping("/{uid}")
    public R info(@PathVariable("uid") String uid) {
        UserEntity user = userService.getById(uid);
        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R save(@RequestBody UserEntity user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        PositionEntity position = positionService.getById(user.getPositionUid());
        if (userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, user.getUsername())) != null) {
            return R.error("账号已存在！");
        }
        if (position.getName().equals("满意度评价人员")) {
            user.setIsGrade(1);
            userService.save(user);
            // 把今年已生成的任务，给这个用户创建
            // 获取今年所有的满意度评价任务
            List<PushGradeEntity> pushList = pushGradeService.list(new LambdaQueryWrapper<PushGradeEntity>().eq(PushGradeEntity::getYear, Calendar.getInstance().get(Calendar.YEAR)));
            // 给用户创建任务
            for (PushGradeEntity insertPush : pushList) {
                gradeDao.insertByUser(insertPush, user.getUid());
            }
        } else {
            userService.save(user);
            // 把今年已生成的任务，给这个用户创建
            List<PushEntity> list = pushService.list(new LambdaQueryWrapper<PushEntity>().eq(PushEntity::getYear, Calendar.getInstance().get(Calendar.YEAR)));
            for (PushEntity pushEntity : list) {
                taskDao.insertByUser(pushEntity, user.getUid());
            }
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R update(@RequestBody UserEntity user) {
        user.setPassword(null);
        UserEntity one = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, user.getUsername()));
        if (!Objects.isNull(one) && !one.getUid().equals(user.getUid())) {
            return R.error("此工号已存在！");
        } else {
            userService.updateById(user);
            return R.ok();
        }
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R delete(@RequestBody String[] uids) {
        if (uids == null || uids.length == 0) {
            return R.error("请选择需要移到不可用的用户");
        }
        List<UserEntity> users = new ArrayList<>();
        Arrays.asList(uids).forEach(i -> {
            users.add(new UserEntity(i, 0));
        });
        userService.updateBatchById(users);
        return R.ok();
    }

    /**
     * 彻底删除
     */
    @PostMapping("/cDelete")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R cDelete(@RequestBody String[] uids) {
        if (uids == null || uids.length == 0) {
            return R.error("请选择需要彻底删除的用户");
        }
        List<UserEntity> users = new ArrayList<>();
        Arrays.asList(uids).forEach(i -> {
            users.add(new UserEntity(i, -1));
        });
        userService.updateBatchById(users);
        return R.ok();
    }

    /**
     * 一键修改密码
     */
    @PostMapping("/resetAllPassword")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R resetAllPassword(@RequestBody String password) {
        return R.ok(userDao.resetAllPassword(passwordEncoder.encode(password)) + "");
    }

    /**
     * 恢复
     */
    @PostMapping("/isT")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R isT(@RequestBody String[] uids) {
        if (uids == null || uids.length == 0) {
            return R.error("请选择需要恢复的用户");
        }
        //获取到部门id，判断这些部门是否是不可用
        List<DepartmentEntity> departmentEntities = userDao.selectDepartmentsByUserUids(uids);
        //获取到职位id，判断这些职位是否是不可用
        List<PositionEntity> positionEntities = userDao.selectPositionsByUserUids(uids);
        //筛选出部门可用的来
        List<String> isDepartmentUid = new ArrayList<>();
        for (DepartmentEntity department : departmentEntities) {
            if (department.getStatus() != 0) {
                isDepartmentUid.add(department.getUid());
            }
        }
        //筛选出职位可用的来
        List<String> isPositionUid = new ArrayList<>();
        for (PositionEntity position : positionEntities) {
            if (position.getStatus() != 0) {
                isPositionUid.add(position.getUid());
            }
        }
        //查询需要恢复的用户
        Collection<UserEntity> users = userService.listByIds(Arrays.asList(uids));
        //将能够恢复的账号选出来
        Collection<UserEntity> isUsers = new ArrayList<>();
        boolean flag;
        for (UserEntity user : users) {
            flag = false;
            for (String s : isDepartmentUid) {
                if (flag) {
                    break;
                }
                for (String s1 : isPositionUid) {
                    if (user.getDepartmentUid().equals(s) && user.getPositionUid().equals(s1)) {
                        user.setStatus(1);
                        isUsers.add(user);
                        flag = true;
                        break;
                    }
                }
            }
        }
        //更新用户状态
        if (isUsers.size() > 0) {
            userService.updateBatchById(isUsers);
        } else {
            return R.error("请先将用户所在的部门或职位设为可用");
        }
        return R.ok().put("msg", "成功恢复个数：" + isUsers.size() + " 共有：" + uids.length + "个(其余不成功则需要先恢复其所在部门或职位)");
    }

}
